package com.rkc.controller;

import com.google.code.kaptcha.Producer;
import com.rkc.enums.BizCodeEnum;
import com.rkc.enums.SendCodeEnum;
import com.rkc.service.NotifyService;
import com.rkc.utils.CommonUtil;
import com.rkc.utils.JsonData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author `RKC`
 * @date 2021/10/10 15:05
 */
@Api(tags = "通知模块")
@RestController
@Slf4j
@RequestMapping("/api/notify/v1")
public class NotifyController {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private NotifyService notifyService;

    /**
     * 图形验证码有效期10分钟
     */
    private static final long CAPTCHA_CODE_EXPIRE = 60 * 1000 * 10;

    @ApiOperation("获取图形验证码")
    @GetMapping("captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        String text = captchaProducer.createText();
        log.info("图形验证码：{}", text);
        //存放在redis中
        stringRedisTemplate.opsForValue().set(getCaptchaKey(request), text, CAPTCHA_CODE_EXPIRE, TimeUnit.MILLISECONDS);
        //图形验证码写入到response中
        BufferedImage bufferedImage = captchaProducer.createImage(text);
        try (ServletOutputStream sos = response.getOutputStream()) {
            ImageIO.write(bufferedImage, "jpg", sos);
        } catch (IOException e) {
            log.error("获取图形验证码异常：{}", e);
        }
    }

    private String getCaptchaKey(HttpServletRequest request) {
        String ip = CommonUtil.getIpAddress(request);
        String userAgent = request.getHeader("User-Agent");
        String key = "user-service:captcha:" + CommonUtil.encryptMD5(ip + userAgent);
        log.info("ip={}", ip);
        log.info("User-Agent={}", userAgent);
        log.info("key={}", key);
        return key;
    }

    /**
     * 发送验证码，需要图形验证码匹配才允许发送
     * @param to 接收方
     * @param captcha 图形验证码
     * @return
     */
    @ApiOperation("发送邮箱验证码")
    @GetMapping("send_code")
    public JsonData sendRegisterCode(@RequestParam("to") String to, @RequestParam("captcha") String captcha, HttpServletRequest request) {
        String captchaKey = getCaptchaKey(request);
        //得到redis中的图形验证码并进行匹配
        String cacheCaptcha = stringRedisTemplate.opsForValue().get(captchaKey);
        if (!Objects.isNull(cacheCaptcha) && captcha.equals(cacheCaptcha)) {
            JsonData sendCode = notifyService.sendCode(SendCodeEnum.USER_REGISTER, to);
            if (sendCode.getCode() == 0) {
                //验证都完成，删除key
                stringRedisTemplate.delete(captchaKey);
            }
            return sendCode;
        }
        return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
    }
}
